package com.lingo.mgr.listener;


import cn.xfyun.api.IseClient;
import cn.xfyun.api.LfasrClient;
import cn.xfyun.config.LfasrTaskStatusEnum;
import cn.xfyun.model.response.ise.IseResponseData;
import cn.xfyun.model.response.lfasr.LfasrMessage;
import cn.xfyun.service.ise.AbstractIseWebSocketListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lingo.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import okhttp3.WebSocket;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileNotFoundException;
import java.net.MalformedURLException;
import java.nio.charset.StandardCharsets;
import java.security.SignatureException;
import java.util.Base64;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class IseClientListener {

    @Value("${xfyun.appId}")
    private String appId;
    @Value("${xfyun.apiKey}")
    private String apiKey;
    @Value("${xfyun.apiSecret}")
    private String apiSecret;

    private ThreadLocal<String> audioEvaluationRes = new ThreadLocal<>();

    /**
     * 解码
     */
    private final static Base64.Decoder decoder = Base64.getDecoder();


    /**
     * 讯飞音频评测
     * @param audioPath（音频文件地址url）
     * @param audioText（音频文本内容）
     * @param ent（语言）
     * @param category（类型）
     * @return
     * @throws FileNotFoundException
     * @throws MalformedURLException
     * @throws SignatureException
     */
    public String audioEvaluation(String audioPath,String audioText,String ent,String category) throws FileNotFoundException, MalformedURLException, SignatureException {
        IseClient client = new IseClient.Builder()
            .signature(appId, apiKey, apiSecret)
            .addSub("ise")
            .addEnt(StringUtils.isNotEmpty(ent) ? ent:"cn_vip")
            .addCategory(StringUtils.isNotEmpty(category) ? ent:"read_sentence")
            .addTte("utf-8")
            .addText('\uFEFF' + audioText)
            .addRstcd("utf8")
            .build();

        File file = new File(audioPath);
        client.send(file, new AbstractIseWebSocketListener() {

            @Override
            public void onSuccess(WebSocket webSocket, IseResponseData iseResponseData) {
                log.info("sid:" + iseResponseData.getSid() + "\n最终识别结果:\n" + new String(decoder.decode(iseResponseData.getData().getData()), StandardCharsets.UTF_8));
                audioEvaluationRes.set(new String(decoder.decode(iseResponseData.getData().getData()), StandardCharsets.UTF_8));
                System.exit(0);
            }

            @Override
            public void onFail(WebSocket webSocket, Throwable throwable, Response response) {
                log.info("音频评测失败:{}",response);
            }
        });
        return audioEvaluationRes.get();
    }

    public String audioToText(String audioPath) throws SignatureException, InterruptedException {
        //1、创建客户端实例
        LfasrClient lfasrClient = new LfasrClient.Builder(appId, apiSecret).slice(102400).build();

        //2、上传
        LfasrMessage task = lfasrClient.upload(audioPath);
        String taskId = task.getData();
        log.info("转写任务 taskId：" + taskId);


        //3、查看转写进度
        int status = 0;
        while (LfasrTaskStatusEnum.STATUS_9.getKey() != status) {
            LfasrMessage message = lfasrClient.getProgress(taskId);

            log.info(message.toString());
            Gson gson = new Gson();
            Map<String, String> map = gson.fromJson(message.getData(), new TypeToken<Map<String, String>>() {
            }.getType());
            status = Integer.parseInt(map.get("status"));
            TimeUnit.SECONDS.sleep(2);
        }
        //4、获取结果
        LfasrMessage result = lfasrClient.getResult(taskId);
        log.info("转写结果: \n" + result.getData());
        System.exit(0);
        return result.getData();
    }
}
